<template>
    <div>
      <el-drawer :model-value="visible" title="项目信息" size="700px" @close="closeHandle" @closed="closed">
        <div class="demo-drawer__content">
          <el-form :model="form" ref="formRef" :rules="formRules" label-position="right">
            <el-form-item label="资料类型" required :label-width="formLabelWidth">
              <el-radio-group v-model="radio" @change="changeRadio">
                <el-radio :label="item" v-for="(item, index) in company" :key="index"> {{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 选择完之后返回 -->
            <el-form-item label="资料配置" prop="ziliao_type" :label-width="formLabelWidth">
              <el-select v-model="form.ziliao_type" default-first-option :reserve-keyword="false"
                         placeholder="请选择资料配置" @change="changeClick">
                <el-option v-for="item in platformTypeData" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item prop="valueHtml" label-position='left' label="资料内容" :label-width="formLabelWidth">
              <!-- <el-input placeholder="请输入资料内容" v-model="form.content" show-word-limit rows="4" type="textarea"
                   autocomplete="off"/> -->
              <div style="border: 1px solid #ccc">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                         :defaultConfig="toolbarConfig" :mode="mode"/>
                <Editor style="height: 500px; overflow-y: hidden;" v-model="form.valueHtml"
                        :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated"/>
              </div>
            </el-form-item>
            <!-- 上传多张图片 和文件 -->
            <el-form-item label="上传图片" :label-width="formLabelWidth">
              <el-upload v-model:file-list="fileList2" class="upload-demo" :headers="headerObj"
                         action="/api/common/upload" :on-preview="handlePreview" :on-remove="handleRemove"
                         :on-success="successUpdata" list-type="picture">
                <el-button type="primary">点击上传图片</el-button>
              </el-upload>
            </el-form-item>
            <!-- 上传文件 -->
            <el-form-item label="上传文件" :label-width="formLabelWidth">
              <el-upload v-model:file-list="fileList" class="upload-demo" action="/api/common/upload" multiple
                         :headers="headerObj" :on-success="successFile" :on-remove="handleRemove2" :limit="3">
                <el-button type="primary">点击上传文件</el-button>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-space>
            <el-button type="info" plain :loading="loading" @click="cancelHandle">取消</el-button>
            <el-button type="primary" :loading="loading" @click="confirmHandle">提交保存</el-button>
          </el-space>
        </template>
      </el-drawer>
    </div>
  </template>
  
  <script setup>
  import getConf from '@/views/news-upload/conf.js'
  import {ref, reactive, computed, watch, onBeforeUnmount, shallowRef, onMounted, onActivated} from "vue";
  import {getUsers} from "@/api/user";
  import {addProject, editProject} from "@/api/project";
  import {platformInformation, platformType, uploadImage, addInformation} from '@/api/information'
  import {uploadImages} from '@/api/news.js'
  import {listsnopage} from "@/api/service.js"
  import {STATUS_ENUM} from "@/views/project-list/status";
  import {toast} from "@/hook/toast";
  import {delay} from "@/utils";
  import store from '@/store'
  import {ElMessage} from "element-plus";
  
  import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  
  const editorRef = shallowRef()
  
  const FILE_LIST = ref([])
  
  const toolbarConfig = {}
  
  const getFilename = (src) => {
    const reg = /^[\s\S]+\/static\/([\s\S]+)$/
    const srcExec = reg.exec(src)
    if (srcExec) {
      return srcExec[1]
    }
  }
  
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: getConf(
        (src) => {
          const name = getFilename(src)
          if (name) {
            FILE_LIST.push(name)
          }
        },
    ),
  }
  
  
  const mode = 'default'
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
  const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
  }
  // 上传图片的地址
  // editorConfig.MENU_CONF['uploadImages'] = {
  //      server: '/common/upload',
  // }
  
  
  const form = reactive({
    // 客户资料
    xiangmu_id: '',
    ziliao_id: "",
    content: "",
    xiangmuziliao_id: '',
    ziliao_type: '',
    images: [],
    files: [],
    valueHtml: '',
  });
  const formRules = computed(() => ({
    name: [
      {
        required: true,
        message: '请输入项目名称',
        trigger: 'change',
      }
    ],
    gongqi: [
      {
        required: true,
        message: '请输入工期',
        trigger: 'change',
      }
    ],
    ziliao_type: [
      {
        required: true,
        message: '请选择资料配置',
        trigger: 'change',
      }
    ],
    valueHtml: [
      {
        required: true,
        message: '请输入资料内容',
        trigger: 'change',
      },
      {
        trigger: 'change',
        validator: (_, value, cb) => {
          if (value === '<p><br></p>') return cb(new Error('请输入资料内容'))
          return cb()
        }
      }
    ]
  }))
  const formRef = ref(null)
  const loading = ref(false);
  const radio = ref('客户资料')
  // 定义上传图片数组
  const fileList = ref([])
  // 定义上传 文件
  const fileList2 = ref([])
  // token
  const headerObj = ref({})
  const {hasLogin, token} = store.getters
  headerObj.value.token = token;
  // 上传图片 后
  function handleRemove(uploadFile, uploadFiles,index) {
    imagess.value = []
  }
  // 上传文件清空
  function handleRemove2(){
    filess.value = []
  }
  
  // 查看图片
  function handlePreview(file) {
  
  
  }
  
  const images = ref([])
  const imagess = ref([])
  
  
  // 上传图片后展示
  function successUpdata(e) {
    imagess.value.push(e.data.fullurl)
  }
  
  const files = ref([])
  const filess = ref([])
  
  // 上传文件
  function successFile(e) {
    console.log(e,'上传文件路径')
    filess.value.push(e.data.fullurl)
  }
  
  const size = ref("default");
  const formLabelWidth = "80px";
  const statusEnum = computed(() => STATUS_ENUM)
  const props = defineProps({
    modelValue: {
      type: Boolean,
      required: true,
    }
  })
  const emits = defineEmits(['update:modelValue', 'addSuccess'])
  
  const cancelHandle = () => {
    visible.value = false
  }
  
  function closed() {
    resetForm()
  }
  
  const imageUrl = ref('')
  
  // 触发单选
  function changeRadio(e) {
    // 选择单选完之后
    radio.value = e
    getPlatform()
  }
  
  const visible = computed({
    get() {
      return props.modelValue
    },
    set(value) {
      emits('update:modelValue', value)
    }
  })
  const userList = ref([])
  
  async function initUserList() {
    const resp = await getUsers()
    const {code, data, msg} = resp
    if (code !== 1) return
    if (!!data && data.length) {
      userList.value = data.map(item => {
        const {id, nickname} = item
        return {value: id, label: nickname}
      })
    }
  }
  
  // 获取公司列表
  const company = ref([])
  
  async function companyList() {
    const resp = await platformInformation()
  
    const {code, data, msg} = resp
    if (code !== 1) return
    company.value = data
  }
  
  // 获取资料
  const platformTypeData = ref([])
  
  async function getPlatform() {
    platformTypeData.value = [];
    const ziliao_type = radio.value
    const resp = await platformType({ziliao_type})
    const {code, data} = resp
    if (code !== 1) return
    if (!!data && data.length) {
      platformTypeData.value = data.map(item => {
        const {id, name} = item
        return {value: id, label: name}
      })
    }
  }
  
  const ziliao_ids = ref('')
  
  // 选择资料的时候
  function changeClick(e) {
    ziliao_ids.value = e
  }
  
  // 清空数据
  function resetForm() {
    form.images = []
    form.files = []
    imagess.value = []
    filess.value = []
    fileList.value = []
    fileList2.value = []
    form.ziliao_type = ''
    editorRef.value.clear()
    radio.value = '客户资料'
    form.xiangmuziliao_id = ''
    formRef.value.resetFields()
  }
  
  watch(() => props.modelValue, value => {
    if (!value) {
      return
    }
    initUserList()
    companyList()
    getPlatform()
  })
  
  const closeHandle = () => {
    visible.value = false
  };
  
  function editHandle(row) {
    const {
      files,
      content,
      id,
      images,
      xiangmu_id,
      ziliao_title,
      ziliao_type,
      ziliao_id
    } = row
    form.xiangmu_id = xiangmu_id
    form.xiangmuziliao_id = id || ''
    form.ziliao_id = ziliao_id
    form.ziliao_type = ziliao_title
    radio.value = ziliao_type || '客户资料'
    if (!isNaN(row)) {
      form.xiangmu_id = row
    }
    if (content) {
      form.valueHtml = decodeURIComponent(content) || '';
    }
    if (images) {
      console.log(images,'tup')
      if(images[0]==''){
        fileList2.value = []
      }else{
        fileList2.value = images.map(item => ({
        name: '1.png',
        url: item
      }))
      }
      const actionss = []
       images.map(item=>{
        actionss.push(item)
      })
      console.log(actionss,'查看的数据')
      imagess.value = actionss
      console.log(imagess.value,'图片路径展示')
    }
    if (files) {
      
      if(files[0]==''){
        fileList.value = []
      }else{
        fileList.value = files.map(item => ({
        name: '1',
        url: item
      }))
    }
      console.log('执行到这')
      const filseActive = []
      files.map(item=>{
        console.log(item,'文件路径')
        filseActive.push(item)
      })
      console.log(filseActive,'查看的数据')
      filess.value = filseActive
      console.log(filess.value,'文件')
  
  
  
  
  
  
      
    }
    visible.value = true
    form.isEdit = true
  }
  
  function editDoos(e) {
    radio.value = e;
  }
  
  defineExpose({
    editHandle,
    editDoos
  })
  
  function reqMethod(data) {
    if (form.isEdit) return editProject(data)
    return addProject(data)
  }
  
  function confirmHandle() {
    formRef.value.validate(async flag => {
      if (!flag) return
      let htmlVl = ''
      if (form.valueHtml !== '<p><br></p>') {
        htmlVl = encodeURIComponent(form.valueHtml)
      }
      if (!htmlVl) return ElMessage.error({
        message: '请输入资料内容'
      })
      loading.value = true
      const {xiangmu_id, ziliao_id, content, xiangmuziliao_id} = form
      console.log(imagess,'文件')
      const a = imagess.value.toString()
      const b = filess.value.toString()
      let cssf = ''
      let cssd = ''
      if(a.charAt(0)==','){
        cssf = a.slice(1)
      }else{
        console.log(a,'参数')
        cssf = a
      }
      if(b.charAt(0)==','){
        cssd = b.slice(1)
      }else{
        cssd = b
      }
      const payload = {
        xiangmu_id, ziliao_id, content: htmlVl, xiangmuziliao_id, images: cssf, files: cssd
      }
      payload.ziliao_id = ziliao_ids.value || ziliao_id
      loading.value = false
      console.log('payload',payload)
      const resp = await addInformation(payload)
      form.isEdit = false
      const {code, msg} = resp
      await delay(200)
      toast({title: msg})
      loading.value = false
      if (code !== 1) return
      triggerUpdate()
    })
  }
  
  function triggerUpdate() {
    emits('addSuccess')
    resetForm()
    visible.value = false
  }
  </script>
  